import { ElMessage } from 'element-plus';
import { useEventBus } from '@/hooks';
import { computed, onBeforeUnmount } from 'vue';
import { onMounted, ref } from 'vue';

interface IUploadTask {
    name: string
    percent: number
    complete: boolean
}

/**
* @title 监听上传任务的钩子 
*/
function useUploadTask() {

    const emitter = useEventBus()

    

    const uploadTaskList = ref<IUploadTask[]>([])

    const uploadTaskNumber = computed(()=>{
        return uploadTaskList.value.length
    })

    onMounted(() => {
        emitter?.on('uploadProgress', (task) => {


            const idx = findTaskIndex(task.name)

            if (idx > -1) {
                uploadTaskList.value[idx] = task
            } else {
                uploadTaskList.value.push(task)
            }
        })

        emitter?.on('uploadSuccess', info => {
            const idx = findTaskIndex(info.name)


            if (idx >= 0) {

                uploadTaskList.value[idx].percent = 100
                uploadTaskList.value[idx].complete = true

                ElMessage.success(`${info.name}上传任务完成`)

                // uploadTaskList.value.splice(idx, 1)
            }
        })
    })


    onBeforeUnmount(() => {
        emitter?.off('uploadProgress')
        emitter?.off('uploadSuccess')
    })

    function findTaskIndex(name: string) {
        const idx = uploadTaskList.value.findIndex(t => {
            return t.name == name
        })

        return idx
    }

    const hasTaskUploading = computed(() => {
        return uploadTaskList.value.length > 0
    })

    function deleteUploadTask(name: string) {
        const idx = findTaskIndex(name)
        uploadTaskList.value.splice(idx, 1)
    }

    return {
        uploadTaskList,
        hasTaskUploading,
        deleteUploadTask,
        uploadTaskNumber,
    }
}

export default useUploadTask